/**
 * Returns true if there is an element in this array that is also in [other]. This method terminates
 * if any intersection is found. The sizes of both arguments are assumed to be so small, and the
 * likelihood of an intersection so great, that it is not worth the CPU cost of sorting or the
 * memory cost of hashing.
 */

export function ArrayIsEquals<T>(one: T[] | readonly T[], other: T[] | readonly T[]): boolean{
  if (one.length !== other.length) return false;
  for (let i = 0; i < one.length; i++) {
    if (one[i] !== other[i]) {
      return false;
    }
  }
  return true;
}

export function hasIntersection(first: string[], second?: string[]): boolean {
  if (first.length === 0 || second === null || second === undefined || second.length === 0){
    return false
  }
  for (const a of first) {
    for (const b of second) {
      if (a === b){
        return true
      }
    }
  }
  return false
}

export function intersect<T>(arrayA: T[], arrayB: T[], comparator: (a: T, b: T) => number): T[] {
  // 使用 Set 去重并求交集
  const setB = new Set(arrayB);
  const intersection = new Set(arrayA.filter(item => setB.has(item)));

  // 转为数组并排序
  return Array.from(intersection).sort(comparator);
}

export function naturalOrder(a: string, b: string): number{
  return a < b ? -1 : a > b ? 1 : 0;
};

/**
 * 在已排序数组中使用二分查找，返回目标值的索引。
 * 如果未找到，返回 -(insertionPoint + 1)
 *
 * @param array 已按 comparator 排序的数组
 * @param value 要查找的值
 * @param comparator 比较函数 (a, b) => -1 | 0 | 1
 * @returns 索引或负数（插入位置编码）
 */
export function binarySearch<T>(
  array: T[],
  value: T,
  comparator: (a: T, b: T) => number
): number {
  let low = 0;
  let high = array.length - 1;

  while (low <= high) {
    const mid = Math.floor((low + high) / 2);
    const compareResult = comparator(array[mid], value);

    if (compareResult < 0) {
      low = mid + 1;
    } else if (compareResult > 0) {
      high = mid - 1;
    } else {
      return mid; // 找到了
    }
  }

  // 未找到，返回插入位置的负编码
  return -(low + 1);
}

/**
 * 比较两个字符串数组是否相等
 * 
 * @param a 第一个数组
 * @param b 第二个数组
 * @returns 如果两个数组相等返回 true，否则返回 false
 */
export function arraysEqual(a?: string[], b?: string[]): boolean {
  if (a === b) return true;
  if (a === null || a === undefined || b === null || b === undefined) return false;
  if (a.length !== b.length) return false;
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) return false;
  }
  return true;
}

/**
 * 计算数组的哈希码
 * 
 * @param arr 字符串数组
 * @returns 数组的哈希码
 */
export function arrayHashCode(arr?: string[]): number {
  if (arr === null || arr === undefined) return 0;
  let result = 1;
  for (const element of arr) {
    result = 31 * result + stringHashCode(element);
  }
  return result;
}

/**
 * 计算字符串的哈希码（使用 Java String.hashCode 算法）
 * 
 * @param str 字符串
 * @returns 字符串的哈希码
 */
export function stringHashCode(str: string): number {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = (31 * hash + str.charCodeAt(i)) | 0;
  }
  return hash;
}